<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';

import { defineEmits, watch } from 'vue';

import { Button, message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';

interface DictOption {
  label: string;
  value: string;
  id?: number;
}

interface Props {
  value?: DictOption[] | string;
}

interface Emits {
  (e: 'update:value', value: DictOption[]): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 解析dictOptions到表格数据，支持数组和字符串格式
const parseDictOptions = (value: DictOption[] | string = ''): DictOption[] => {
  if (!value) return [];

  // 如果已经是数组，直接返回
  if (Array.isArray(value)) {
    return value;
  }

  // 如果是字符串，解析JSON
  if (typeof value === 'string') {
    try {
      return JSON.parse(value) as DictOption[];
    } catch {
      return [];
    }
  }

  return [];
};

// 将表格数据转换为数组格式
const formatDictOptions = (data: DictOption[]): DictOption[] => {
  return data;
};

// 表格配置
const gridOptions: VxeGridProps<DictOption> = {
  columns: [
    { type: 'seq', title: '序号', width: 60 },
    {
      field: 'label',
      title: '标签',
      editRender: { name: 'input' },
      minWidth: '120px',
    },
    {
      field: 'value',
      title: '值',
      editRender: { name: 'input' },
      minWidth: '100px',
    },
    {
      slots: { default: 'action' },
      title: '操作',
      width: '80px',
      align: 'center',
    },
  ],
  data: [] as DictOption[],
  editConfig: {
    mode: 'row',
    trigger: 'click',
    showStatus: true,
  },
  height: 400,
  keepSource: true,
  showOverflow: true,
  autoResize: true,
  rowConfig: {
    keyField: 'id',
  },
  toolbarConfig: {
    slots: {
      buttons: 'toolbar_buttons',
    },
  },
  pagerConfig: {
    enabled: false,
  },
};

// 保存行（编辑后同步数据）
const saveRowEvent = async ({ row }: { row: DictOption }) => {
  // 验证数据
  if (!row.label || !row.value) {
    message.warning('标签和值不能为空');
    return;
  }

  // 检查重复
  const currentTableData = gridApi.grid?.getTableData().tableData || [];
  const duplicate = currentTableData.find(
    (item) =>
      item !== row && (item.label === row.label || item.value === row.value),
  );

  if (duplicate) {
    message.warning('标签或值已存在');
    return;
  }

  await gridApi.grid?.clearEdit();

  // 同步数据到父组件
  const updatedTableData = gridApi.grid?.getTableData().tableData || [];
  const formattedValue = formatDictOptions(updatedTableData);
  emit('update:value', formattedValue);
  message.success(`${row.label}已更新`);
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions,
  gridEvents: {
    editClosed: saveRowEvent,
  },
});

// 添加新行
const addRowEvent = () => {
  const newRow: DictOption = {
    label: '',
    value: '',
    id: Date.now(),
  };

  gridApi.grid?.insertAt(newRow, -1);
};

// 删除行
const deleteRowEvent = async (row: DictOption) => {
  await gridApi.grid?.remove(row);
  message.success('删除成功');

  // 同步数据到父组件
  const updatedTableData = gridApi.grid?.getTableData().tableData || [];
  const formattedValue = formatDictOptions(updatedTableData);
  emit('update:value', formattedValue);
};

// 监听value变化，刷新表格数据
watch(
  () => props.value,
  (newValue) => {
    // 如果已经是数组，直接使用；如果是字符串，解析后使用
    const data = Array.isArray(newValue)
      ? newValue
      : parseDictOptions(newValue);
    gridApi.setGridOptions({ data });
  },
  { immediate: true },
);
</script>

<template>
  <div class="dict-options-table">
    <Grid>
      <!-- 工具栏按钮 -->
      <template #toolbar_buttons>
        <Button type="primary" @click="addRowEvent">新增</Button>
      </template>

      <!-- 操作列 -->
      <template #action="{ row }">
        <Button type="link" danger @click="deleteRowEvent(row)">删除</Button>
      </template>
    </Grid>
  </div>
</template>

<style scoped>
.dict-options-table {
  width: 100%;
}

.dict-options-table :deep(.vxe-toolbar) {
  margin-bottom: 8px;
}

.dict-options-table :deep(.vxe-button--wrapper) {
  padding: 0;
}
</style>
